<?php

namespace web\common\utils;

/**
 * 微信授权
 */
class Oauth {

    public $appId;
    public $appSecret;

    function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    /**
     * 获取微信授权链接
     * 
     * @param string $redirect_uri 跳转地址
     * @param string $scope 
     * @param string $state 参数
     */
    public function getAuthorizeUrl($redirect_uri, $scope, $state = '') {
        $_redirect_uri = urlencode($redirect_uri);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appId . '&redirect_uri=' . $_redirect_uri . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        return $url;
    }

    /**
     * 通过code换取网页授权token
     * @param type $code
     * @return type
     */
    public function getToken($code) {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appId . '&secret=' . $this->appSecret . '&code=' . $code . '&grant_type=authorization_code';
        $result = file_get_contents($url);
        $json = json_decode($result, true);
        return $json;
    }

    /**
     * 刷新access_token（如果需要）
     * @param type $refresh_token 填写通过access_token获取到的refresh_token参数
     * @return type
     */
    public function refreshToken($refresh_token) {
        $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $this->appId . '&grant_type=refresh_token&refresh_token=' . $refresh_token;
        $result = file_get_contents($url);
        $json = json_decode($result, true);
        return $json;
    }

    /**
     * 检验授权凭证（access_token）是否有效。
     * @param type $access_token 网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
     * @param type $openid 用户的唯一标识
     * @return type
     */
    public function authAccessToken($access_token, $openid) {
        $url = 'https://api.weixin.qq.com/sns/auth?access_token=' . $access_token . '&openid=' . $openid;
        $result = file_get_contents($url);
        $json = json_decode($result, true);
        return $json;
    }

    /**
     * 拉取用户信息(需scope为 snsapi_userinfo)。
     * 如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了。
     * @param string $access_token 网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
     * @param string $openid 用户的唯一标识
     */
    public function getUserInfo($access_token, $openid) {
        if ($access_token && $openid) {
            $access_info = $this->authAccessToken($access_token, $openid);
            if ($access_info['errcode'] != '0') {
                exit('页面已过期');
            }
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
            $data = file_get_contents($url);
            return json_decode($data, true);
        }
        return false;
    }

}
